// src/apiService/xunfeiAPI.js
import axios from 'axios';
import apiConfig from '@/config/apiConfig';

// 创建一个 axios 实例
const apiClient = axios.create({
  baseURL: apiConfig.baseURL, // 使用配置文件中的 baseURL
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiConfig.apiKey}`,
  },
});

// 封装 GET 请求
export const get = async (url, params = {}) => {
  try {
    const response = await apiClient.get(url, { params });
    return response.data;
  } catch (error) {
    handleError(error);
  }
};

// 封装 POST 请求
export const post = async (url, data = {}) => {
  try {
    const response = await apiClient.post(url, data);
    return response.data;
  } catch (error) {
    handleError(error);
  }
};

// 封装 PUT 请求
export const put = async (url, data = {}) => {
  try {
    const response = await apiClient.put(url, data);
    return response.data;
  } catch (error) {
    handleError(error);
  }
};

// 封装 DELETE 请求
export const del = async (url) => {
  try {
    const response = await apiClient.delete(url);
    return response.data;
  } catch (error) {
    handleError(error);
  }
};

// 错误处理函数
const handleError = (error) => {
  console.error('API Error:', error);
  throw error;
};

// 处理响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      // 处理常见的响应错误
      switch (error.response.status) {
        case 401:
          // 未授权，重定向到登录页面
          window.location = '/login';
          break;
        case 500:
          // 服务器错误
          alert('服务器错误，请稍后再试');
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
);